from PyQt6.QtWidgets import QListWidget,QListWidgetItem,QWidget,QHBoxLayout,QCheckBox,QSpacerItem,QLabel,QVBoxLayout
from PyQt6.QtWidgets import QApplication,QSizePolicy,QPushButton
from PyQt6.QtCore import QSize,Qt
from PyQt6.QtGui import QIcon
import sys,os
from utils.Logger import LogPrint
from utils import ImageUtils

class MultiChoiceListWidget(QListWidget):


    def __init__(self,parent=None):
        super().__init__(parent=parent)
        self.setStyleSheet("QListWidget::item{height:50px;}")  # 设置每行的高度
        self.setFixedSize(QSize(170,400))
        self.setSpacing(5)
        self.setSelectionMode(QListWidget.SelectionMode.MultiSelection)
        # 设置 QListWidget 的点击信号到自定义的槽函数
        self.itemClicked.connect(self.onItemClicked)
        self.itemSelectionChanged.connect(self.onItemSelectChange)

        #当前选中item
        self.currentSelectItem=''
        #点击回调
        self.onItemClickedCallback=None


    def setItemClickedCallback(self,callback):
        self.onItemClickedCallback=callback
 
    def addItem(self, text):
        item = QListWidgetItem(self)
        widget = QWidget()
        #widget.setStyleSheet("background-color:gray")
        layout = QHBoxLayout()
        #layout.setAlignment(Qt.AlignmentFlag.a)
        checkbox=QCheckBox(parent=widget)
        dirname, filename = os.path.split(text)
        checkbox.setObjectName(text)
        checkbox.setText(filename)
        #checkbox状态和list行关联
        #checkbox.stateChanged.connect(self.onCheckboxStatusChange)
        #checkbox.clicked.connect(self.onCheckboxClicked)
        checkbox.clicked.connect(lambda: self.onCheckboxClickedLambda(checkbox))
        
        # 创建一个伸缩空间项，用于在左边按钮和右边按钮之间添加空白
        spacerLeft = QSpacerItem(60, 20, QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum)
        button = QPushButton()
        button.setFixedSize(QSize(20,20))
        button.setFlat(True)
        # 创建一个伸缩空间项，用于在右边按钮和布局边缘之间添加空白
        spacerRight = QSpacerItem(20, 20, QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum)
        button.setIcon(ImageUtils.getQIcon('icon_delete.svg'))
        #button.clicked.connect(self.onClickedBtnRemove)
        button.setProperty('id',text)
        button.setObjectName(text)
        button.clicked.connect(lambda: self.onClickedBtnRemoveLambda(button))
        button.setEnabled(False)
        layout.addWidget(checkbox)
        layout.addItem(spacerLeft)
        layout.addWidget(button)
        layout.addItem(spacerRight)
        widget.setLayout(layout)
        item.setData(Qt.ItemDataRole.UserRole,text)
    
        self.setItemWidget(item, widget)

        item.listWidget()

    def onCheckboxStatusChange(self,state):

        # 如果checkbox被选中
        if state == Qt.CheckState.Checked:
            # 这里可以实现你需要的功能，比如选中所有行
            for row in range(self.count()):
                item=self.item(row)
                itemWidget=self.itemWidget(item)
                if itemWidget:
                    checkbox=itemWidget.findChildren(QCheckBox)[0]
                    if checkbox.isChecked():
                        item.setSelected(True)

        else:
            # 如果checkbox没有被选中，则可以取消选中所有行
            for row in range(self.count()):
                self.item(row).setSelected(False)
        # 获取被点击的项的行号
        selectItemList=self.selectedItems()
        for item in selectItemList:
            LogPrint.info(item.data())
        row = self.currentRow()
        LogPrint.info('onCheckboxStatusChange',row,state)

    def onCheckboxClicked(self,state):

        LogPrint.info('onCheckboxClicked',state)

        # 如果checkbox被选中
        if state:
            # 这里可以实现你需要的功能，比如选中所有行
            for row in range(self.count()):
                item=self.item(row)
                itemWidget=self.itemWidget(item)
                if itemWidget:
                    checkbox=itemWidget.findChildren(QCheckBox)[0]
                    if checkbox.isChecked():
                        item.setSelected(True)
                        self.setCurrentSelectItemText(checkbox.objectName())
                        #通知上个界面
                        if self.onItemClickedCallback:
                            self.onItemClickedCallback(checkbox.objectName())

        else:
            # 如果checkbox没有被选中，则可以取消选中
            for row in range(self.count()):
                item=self.item(row)
                itemWidget=self.itemWidget(item)
                if itemWidget:
                    checkbox=itemWidget.findChildren(QCheckBox)[0]
                    if checkbox.isChecked() == False:                        
                        item.setSelected(False)
                        self.setCurrentSelectItemText(None)
            #通知上个界面
            if self.onItemClickedCallback:
                self.onItemClickedCallback(self.currentSelectItem)

        row = self.currentRow()
        self.currentItem()
        LogPrint.info('onCheckboxClicked currentRow',row)

        LogPrint.info('onCheckboxClicked currentSelectItem',self.currentSelectItem)

        LogPrint.info('onCheckboxClicked allSelectItem',self.getSelectItems())

    def onCheckboxClickedLambda(self,checkbox):

        LogPrint.info('onCheckboxClicked',checkbox.objectName())

        # 先设置item的选中状态
        for row in range(self.count()):
            item=self.item(row)
            itemWidget=self.itemWidget(item)
            if itemWidget:
                cb=itemWidget.findChildren(QCheckBox)[0]
                btn=itemWidget.findChildren(QPushButton)[0]
                if cb.isChecked():                        
                    item.setSelected(True)
                    btn.setEnabled(True)
                else:
                    item.setSelected(False)
                    btn.setEnabled(False)

        # 如果checkbox被选中
        if checkbox.isChecked():
            # 这里可以实现你需要的功能，比如选中所有行
            self.setCurrentSelectItemText(checkbox.objectName())
            #通知上个界面
            if self.onItemClickedCallback:
                self.onItemClickedCallback(checkbox.objectName())
        else:
            self.setCurrentSelectItemText(None)
            #通知上个界面
            if self.onItemClickedCallback:
                self.onItemClickedCallback(self.currentSelectItem)

        

        LogPrint.info('onCheckboxClicked currentSelectItem',self.currentSelectItem)

        LogPrint.info('onCheckboxClicked allSelectItem',self.getSelectItems())


    def onItemSelectChange(self):
        row = self.currentRow()
        LogPrint.info('onItemSelectChange currentRow',row)

    def onItemClicked(self,item):
        
        itemText = self.setItemSelected(item)
        #通知上个界面
        if self.onItemClickedCallback:
            self.onItemClickedCallback(itemText)

        row = self.currentRow()
        LogPrint.info('onItemClicked currentRow',row)
        LogPrint.info('onItemClicked currentSelectItem',self.currentSelectItem)
        LogPrint.info('onItemClicked allSelectItem',self.getSelectItems())

    #设置单行选中，手动点击行或者全选时调用
    #status--true,设置全部选中，false--设置全部不选，None--根据已有状态取反
    def setItemSelected(self,item,status=None):
        itemWidget=self.itemWidget(item)
        itemText=None
        if itemWidget:
            checkboxList=itemWidget.findChildren(QCheckBox)
            btnList=itemWidget.findChildren(QPushButton)
            btnRemove=None
            cbSel=None
            
            if btnList and len(btnList) > 0:
                btnRemove=btnList[0]
            if checkboxList and len(checkboxList) > 0:
                cbSel=checkboxList[0]
            itemText=cbSel.objectName()
            #判断status状态
            if status is None:
                if cbSel.isChecked():
                    cbSel.setChecked(False)
                    btnRemove.setEnabled(False)
                    self.setCurrentSelectItemText(None)
                else :
                    cbSel.setChecked(True)   
                    btnRemove.setEnabled(True)
                    self.setCurrentSelectItemText(itemText)
            elif status == True:
                cbSel.setChecked(True)
                self.setCurrentSelectItemText(itemText)
                btnRemove.setEnabled(True)
            elif status ==False:
                cbSel.setChecked(False)
                self.setCurrentSelectItemText(None)
                btnRemove.setEnabled(False)
            
        return itemText

    #全选
    def setSelectAll(self):
        LogPrint.info('selectAllItem')
        self.selectAll()
        items=self.selectedItems()
        for item in items:
            self.setItemSelected(item,status=True)
        items=self.selectedItems()
        LogPrint.info('selectAllItem',len(items))

    #取消全选
    def setClearSelection(self):
        
        items=self.selectedItems()
        for item in items:
            self.setItemSelected(item,status=False)

        self.clearSelection()

    #设置当前选中item，如果当前是取消，则从已有选中项取第一个
    def setCurrentSelectItemText(self,text):
        LogPrint.info('setCurrentSelectItemText text',text)
        if text:
            self.currentSelectItem=text
        else:
            selectList= self.selectedItems()
            if selectList and len(selectList) > 0:
                item=selectList[0]
                itemWidget=self.itemWidget(item)
                if itemWidget:
                    checkbox=itemWidget.findChildren(QCheckBox)[0]
                    LogPrint.info('setCurrentSelectItemText checkbox.objectName()',checkbox.objectName())
                    self.currentSelectItem=checkbox.objectName()
                else:
                    self.currentSelectItem=''
            else:
                self.currentSelectItem=''

    #获取总条数以及选中的条数
    def getItemCount(self):
        total = self.count()
        selectCount = len(self.selectedItems())

        return total,selectCount
  
    
    #获取选中的文件列表
    def getSelectItems(self):
        pdfList=[]
        selectCount = len(self.selectedItems())
        if selectCount > 0:
            items=self.selectedItems()
            for item in items:
                itemWidget=self.itemWidget(item)
                if itemWidget:
                    checkbox=itemWidget.findChildren(QCheckBox)[0]
                    pdfList.append(checkbox.objectName())

        return pdfList


    def removeItem(self,row=-1):
        if row == -1:
            # 获取被点击的项的行号
            row = self.currentRow()
        LogPrint.info('removeItem',row)
        # 删除当前选中的项
        self.takeItem(row)

    def onClickedBtnRemove(self):
        self.removeItem()
    
    def onClickedBtnRemoveLambda(self,button):
        LogPrint.info('onClickedBtnRemoveLambda',button.property('id'))
        #self.removeItem()

        if button.property('id')==self.currentSelectItem:
            self.setCurrentSelectItemText(None)

        for row in range(self.count()):
            item=self.item(row)
            itemWidget=self.itemWidget(item)
            if itemWidget:
                btn=itemWidget.findChildren(QPushButton)[0]
                LogPrint.info(row,btn.property('id'))
                if button.property('id') == btn.property('id'):
                    self.removeItem(row)

        if self.onItemClickedCallback:
            self.onItemClickedCallback(self.currentSelectItem)



class Ui_Form(QWidget):
    def __init__(self):
        super(Ui_Form,self).__init__()
        self.setupUi(self)


    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(310, 500)

        layout=QVBoxLayout(self)
        layout.setAlignment(Qt.AlignmentFlag.AlignTop)

        layoutSelectAll=QHBoxLayout()
        layoutSelectAll.setAlignment(Qt.AlignmentFlag.AlignLeft)
        self.cbSelectAll=QCheckBox('全选')
        self.cbSelectAll.clicked.connect(self.onClickCbSelectAll)
        layoutSelectAll.addWidget(self.cbSelectAll)
        self.labelFileCount=QLabel('0/0')
        layoutSelectAll.addWidget(self.labelFileCount)
        layout.addLayout(layoutSelectAll)

        self.fileListWidget=MultiChoiceListWidget()
        for i in range(5):  # 添加5行数据
           self.fileListWidget.addItem(f"Text {i}")
        self.setFixedSize(QSize(170,200))
        self.fileListWidget.setItemClickedCallback(self.onItemClicked)
        layout.addWidget(self.fileListWidget)

        

    #选中所有
    def onClickCbSelectAll(self,event):
        LogPrint.info('onClickCbSelectAll',event)
        if event:
            self.fileListWidget.setSelectAll()
        else :
            self.fileListWidget.setClearSelection()

        total,selectCount=self.fileListWidget.getItemCount()
        self.labelFileCount.setText(f'{selectCount}/{total}')
        if selectCount < total:
            self.cbSelectAll.setChecked(False)
        else:
            self.cbSelectAll.setChecked(True)

    #选中
    def onItemClicked(self,text):
        total,selectCount=self.fileListWidget.getItemCount()
        self.labelFileCount.setText(f'{selectCount}/{total}')

        if selectCount < total:
            self.cbSelectAll.setChecked(False)
        else:
            self.cbSelectAll.setChecked(True)

        LogPrint.info('onItemClicked',text)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = Ui_Form()    
    main.show()    
    #main.showMaximized()
    sys.exit(app.exec())